package com.majun.huaxishe.utils;


import com.majun.huaxishe.constant.InfoConstant;
import com.majun.huaxishe.exception.UploadException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Data
@ConfigurationProperties(prefix = "minio")
@Component
@Slf4j
public class MinioUtils {

    private String endpoint;

    private String username;

    private String password;

    private String bucketName;

    /**
     * 上传文件到minio
     */
    public String upload2Minio(MultipartFile file,String albumName) {
        try {
            InputStream inputStream = file.getInputStream();
            String realFilename = file.getOriginalFilename();
            String suffix = realFilename.substring(realFilename.lastIndexOf("."));

            //1.创建minio链接客户端
            MinioClient minioClient = MinioClient.
                    builder().
                    credentials(username, password).
                    endpoint(endpoint).
                    build();
            //2.上传
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            if (albumName != null) {
                fileName = albumName + "/" + fileName;
            }
            String type = suffix.replace(".", "");
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(fileName)//文件名
                    .contentType("image/" + type)//文件类型
                    .bucket(bucketName)//桶名词  与minio创建的名词一致
                    .stream(inputStream, inputStream.available(), -1) //文件流
                    .build();
            minioClient.putObject(putObjectArgs);
            return endpoint + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            log.error(e.toString());
            throw new UploadException(InfoConstant.UPLOAD_FAIL);
        }
    }
}
